package Persistencia;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import play.db.jpa.GenericModel;
import play.db.jpa.JPA;

import Persistencia.Exception.DAOException;

public class DAOGenericoJPA<T> implements IDAOGenerico<T> {

    private Class<T> classEntity;

    public DAOGenericoJPA() {
      this.classEntity = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }


    public void addEntity(T entity) throws DAOException {
        EntityManager manager = JPA.em();
        try {
            manager.getTransaction().begin();
            manager.persist(entity);
            manager.getTransaction().commit();
         } catch (Exception e) {
            manager.getTransaction().rollback();
         }
    }

    public void updateEntity(T entity) throws DAOException {
        EntityManager manager = JPA.em();
         try{
             manager.getTransaction().begin();
             manager.flush();
             entity = manager.merge(entity);
             manager.getTransaction().commit();
         } finally {
             manager.close();
         }
    }

    public void removeEntity(T entity) throws DAOException {
        EntityManager manager = JPA.em();
        try{
             manager.getTransaction().begin();
             manager.remove(entity);
             manager.getTransaction().commit();
         } finally {
             manager.getTransaction().rollback();
         }
    }

    public List<T> findAll() throws DAOException {
        EntityManager manager = JPA.em();
        try {
            String query = "select c from " + classEntity.getSimpleName() +" c";
            return manager.createQuery(query).getResultList();
         } catch (Exception e) {
             throw new DAOException(e);
         } finally {
              if (manager != null) { manager.close(); }
         }

    }

    public T findById(Integer id) throws DAOException {
          EntityManager manager = JPA.em();
          try {
             return manager.find(classEntity, id);
          } catch (Exception e) {
             throw new DAOException(e);
          } finally {
             if (manager != null) {
                 manager.close();
             }
          }
    }

}
